package main

import (
	"fmt"
	"strings"
	"time"

	"reflect"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"gopkg.in/mgo.v2/bson"
)

func ApiInit() {
	r := gin.Default() // 创建一个默认的路由引擎
	InitMiddleware(r)
	RouterInit(r)
	r.Run(":8080") // 监听并在 0.0.0.0:8080 上启动服务
}

// ... 已有代码 ...

func StructToBSONM(data interface{}) (bson.M, error) {
	v := reflect.ValueOf(data)
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}

	if v.Kind() != reflect.Struct {
		return nil, fmt.Errorf("expected struct, got %T", data)
	}

	result := bson.M{}
	t := v.Type()

	for i := 0; i < v.NumField(); i++ {
		field := t.Field(i)
		fieldValue := v.Field(i)

		// 跳过零值字段
		if isZeroValue(fieldValue.Interface()) {
			continue
		}

		// 获取bson标签名，如果没有则使用字段名
		key := field.Name
		if tag := field.Tag.Get("bson"); tag != "" {
			if tag == "-" {
				continue // 跳过明确标记忽略的字段
			}
			key = strings.Split(tag, ",")[0]
		}

		result[key] = fieldValue.Interface()
	}

	return result, nil
}

func isZeroValue(v interface{}) bool {
	val := reflect.ValueOf(v)
	switch val.Kind() {
	case reflect.String:
		return val.Len() == 0
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return val.Int() == 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return val.Uint() == 0
	case reflect.Float32, reflect.Float64:
		return val.Float() == 0
	case reflect.Bool:
		return !val.Bool()
	case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan, reflect.Func:
		return val.IsNil()
	case reflect.Struct:
		if t, ok := v.(time.Time); ok {
			return t.IsZero()
		}
		return false
	default:
		return false
	}
}

func Success(c *gin.Context, data interface{}) {
	c.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data":    data,
	})
}

// 成功响应，分页
func SuccessPage(c *gin.Context, data interface{}, total int, page int, pageSize int) {
	Success(c, gin.H{
		"list":     data,
		"total":    total,
		"page":     page,
		"pageSize": pageSize,
	})

}

func Ok(c *gin.Context) {
	c.JSON(200, gin.H{
		"code": 0,
	})
}
func RetCode(c *gin.Context, code int) {
	c.JSON(200, gin.H{
		"code": code,
	})
}

// 错误响应
func Error(c *gin.Context, code int, message string) {
	c.JSON(200, gin.H{
		"code":    code,
		"message": message,
	})
}
func RouterInit(r *gin.Engine) {
	// 注册路由
	BookRouterInit(r)
	ChapterRouterInit(r)
	EleRouterInit(r)

}
func InitMiddleware(r *gin.Engine) {
	// 日志中间件
	r.Use(gin.Logger())

	// CORS配置
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
		AllowHeaders:     []string{"Origin", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))
}
